package com.mall.controller;

import com.mall.common.resp.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author xyl
 * @date 2021-02-09 10:31
 */
@ApiIgnore
@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = PATH)
    ResponseResult error(HttpServletRequest request, HttpServletResponse response) {
        // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring.
        // Here we just define response body.
        Map<String, Object> errorMap = getErrorAttributes(request);
        //定义返回格式
        Integer status = (Integer) Objects.requireNonNull(errorMap.get("status"));
        String message = Objects.requireNonNull(errorMap.get("message")).toString();
        ResponseResult d= new ResponseResult(status, message);
        response.setStatus(HttpServletResponse.SC_OK);
        return d;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        WebRequest requestAttributes = new ServletWebRequest(request);
        return errorAttributes.getErrorAttributes(requestAttributes ,false);
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}